﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace Daneas.Utility.Universals
{
    /// <summary>
    /// cmd命令工具
    /// </summary>
    public class CmdTool
    {
        /// <summary>
        /// ping一个ip，获取返回结果
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static PingParam CmdPing(string ip)
        {
            PingParam list = new PingParam();

            Process process = new Process();

            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.UseShellExecute = false; //关闭Shell的使用
            process.StartInfo.RedirectStandardInput = true;//重定向标准输入
            process.StartInfo.RedirectStandardOutput = true;//重定向标准输出
            process.StartInfo.RedirectStandardError = true;//重定向错误输出
            process.StartInfo.CreateNoWindow = true;//设置不显示窗口
            process.Start();

            process.StandardInput.WriteLine("ping " + ip);
            process.StandardInput.WriteLine("exit");

            string backdata = process.StandardOutput.ReadToEnd().ToLower();
            process.Close();

            PingParam param = new PingParam();
            param.Site = ip;

            if (backdata.IndexOf("could not find host") != -1)
            {
                param.Result = "连接失败，无法找到主机";
            }
            else if (backdata.IndexOf("100% lose") != -1)
            {
                param.Result = "连接成功,数据包丢失完";
            }
            else if (backdata.IndexOf("destination host unreachable") != -1)
            {
                param.Result = "无法到达目的主机";
            }
            else if (backdata.IndexOf("request timed out") != -1)
            {
                param.Result = "请求超时";
            }
            else if (backdata.IndexOf("unknown host") != -1)
            {
                param.Result = "无法解析主机";
            }
            else
            {
                string regTLL = "ttl=(?'ttl'\\d*)";

                string regAvgTime = "average[^<>]=(?'time'[^<>]*)ms";

                param.Result = "连接成功";

                Regex regexTTL = new Regex(regTLL, RegexOptions.IgnoreCase);
                MatchCollection matchs = regexTTL.Matches(backdata);

                double total = 0;
                foreach (Match m in matchs)
                {
                    total += Convert.ToDouble(m.Groups["ttl"].Value);
                }

                param.TTL = Convert.ToInt32(total / matchs.Count);
                param.AvgTime = Convert.ToInt32(new Regex(regAvgTime, RegexOptions.IgnoreCase).Match(backdata).Groups["time"].Value);
                param.Bytes = 32;
            }

            return param;
        }

        /// <summary>
        /// 杀服务器进程
        /// </summary>
        /// <param name="processName">进程名字</param>
        /// <returns></returns>
        public static bool CmdKillProcess(string processName)
        {
            try
            {
                Process[] proc = Process.GetProcessesByName(processName);

                if (proc.Length == 0)
                {
                    return true;
                }

                foreach (var item in proc)
                {
                    item.Kill();
                }

                return true;

            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 执行cmd命令
        /// </summary>
        /// <param name="processStr">命令文本</param>
        /// <returns></returns>
        public static string CmdProcessWork(string processStr)
        {
            try
            {
                Process process = new Process();

                process.StartInfo.FileName = "cmd.exe";
                process.StartInfo.UseShellExecute = false; //关闭Shell的使用
                process.StartInfo.RedirectStandardInput = true;//重定向标准输入
                process.StartInfo.RedirectStandardOutput = true;//重定向标准输出
                process.StartInfo.RedirectStandardError = true;//重定向错误输出
                process.StartInfo.CreateNoWindow = true;//设置不显示窗口
                process.Start();

                process.StandardInput.WriteLine(processStr);
                process.StandardInput.WriteLine("exit");

                string backdata = process.StandardOutput.ReadToEnd().ToLower();
                process.Close();

                return backdata;
            }
            catch (Exception ex)
            {
                return "catch an exception:" + ex.Message;
            }
        }
    }

    public class PingParam
    {
        public PingParam()
        {
            this.Bytes = -1;

            this.AvgTime = -1;

            this.TTL = -1;
        }
        /// <summary>
        /// ping的结果，失败、成功、有问题
        /// </summary>
        public string Result { get; set; }

        public int Bytes { get; set; }

        public int AvgTime { get; set; }

        public int TTL { get; set; }

        public string Site { get; set; }
    }
}
